<template>
  <!-- <div class="index" :class="theme.isDark ? 'theme-dark' : 'theme-day'"> -->
  <div class="index">
    <!-- 引用封装的顶部导航栏组件 -->
    <home-header
      :logoText="logoText"
      :showSerch="showSearch"
      :navLi="navLi"
      :tools="tools"
      :login="user"
      :showThemeChange="theme.show"
      @changeTheme="handleChangeTheme"
      @searchClick="handleSearchClick"
      @user="handleUser"
    ></home-header>
    <main>
      <!-- 设置二级路由 -->
      <router-view></router-view>
    </main>
    <!-- 注册/登录对话框 -->
    <el-dialog
      :title="isSignIn ? '注册' : '登录'"
      :visible.sync="centerDialogVisible"
      width="30%"
      center
    >
      <el-input placeholder="请输入用户名" v-model="loginForm.username">
        <template slot="prepend">用户名</template>
      </el-input>
      <el-input
        show-password
        placeholder="请输入密码"
        v-model="loginForm.password"
      >
        <template slot="prepend">密&nbsp;&nbsp;码</template>
      </el-input>
      <el-input
        v-show="isSignIn"
        placeholder="请输入邮箱"
        v-model="loginForm.email"
      >
        <template slot="prepend">邮&nbsp;&nbsp;箱</template>
      </el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelLogin">取 消</el-button>
        <el-button type="primary" @click="login">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户信息对话框 -->
    <el-dialog
      title="修改用户信息"
      :visible.sync="updateDialogVisible"
      width="30%"
      center
    >
      <!-- 头像上传与回显 -->
      <el-upload
        style="display: flex; justify-content: center"
        name="avatar"
        action="http://localhost:3000/upload/avatar/"
        :show-file-list="true"
        :limit="1"
        :on-exceed="handleImageExeed"
        :before-upload="beforeImageUpload"
        :on-success="handleSuccessUpload"
      >
        <img
          v-if="imageUrl"
          :src="imageUrl"
          style="width: 60px; height: 60px; border-radius: 50px"
        />
        <i v-else class="uploader-tip">点击修改头像</i>
      </el-upload>
      <el-input
        placeholder="请输入用户名"
        disabled
        v-model="updateForm.username"
      >
        <template slot="prepend">用户名</template>
      </el-input>
      <el-input placeholder="请输入昵称" v-model="updateForm.nickname">
        <template slot="prepend">昵&nbsp;&nbsp;称</template>
      </el-input>
      <el-input placeholder="请输入邮箱" v-model="updateForm.email">
        <template slot="prepend">邮&nbsp;&nbsp;箱</template>
      </el-input>
      <el-input
        placeholder="请输入密码"
        v-model="updateForm.password"
        show-password
      >
        <template slot="prepend">密&nbsp;&nbsp;码</template>
      </el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelUpdate">取 消</el-button>
        <el-button type="primary" @click="update">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 返回顶部 -->
    <div class="back-top" :class="backTopShow ? '' : 'hide'">
      <img src="huatop.png" alt="" @click="backTop" />
    </div>
    <!-- 工具栏 -->
    <!-- <div class="util">
      <a href=""><i class="el-icon-s-home"></i></a>
    </div> -->
    <!-- 引用封装的页脚组件 -->
    <home-footer beiAn="">
      <template #text
        >从前我不曾为自己的所作所为而后悔过，唯独对于没做的事，总是追悔莫及。</template
      >
      <template #device>停云 讲你知 娇慎一起开发的哟~</template>
    </home-footer>
  </div>
</template>

<script>
// 导入组件
import HomeHeader from '@/components/HomeHeader.vue'
import HomeFooter from '@/components/HomeFooter.vue'

export default {
  name: 'HomeView',
  components: {
    HomeHeader,
    HomeFooter,
  },
  data() {
    return {
      backTopShow: false,
      // 用于控制整套皮肤的亮度
      // isDark: localStorage.getItem('isDark') == 'true',
      isDark: false,
      themeColor: {
        dayBg:
          'linear-gradient(90deg, rgba(247, 149, 51, 0.1), rgba(243, 112, 85, 0.1) 15%, rgba(239, 78, 123, 0.1) 30%, rgba(161, 102, 171, 0.1) 44%, rgba(80, 115, 184, 0.1) 58%, rgba(16, 152, 173, 0.1) 72%, rgba(7, 179, 155, 0.1) 86%, rgba(109, 186, 130, 0.1))',
        dayFont: '#666',
        dayMask: 'rgba(0,0,0,0.03)',
        dayOpcityDiv: 'rgba(255,255,255,0.8)',
        dayDiv: 'rgba(255, 255, 255, 0.9)',
        dayWeatherBgc: 'ffffff',
        dayWeatherFont: '000000',
        darkBg: '#121212',
        darkFont: 'hsla(0, 0%, 100%, 0.8)',
        darkMask: 'rgba(51,51,51,0.5)',
        darkOpcityDiv: 'rgba(0,0,0,0.5)',
        darkDiv: 'rgba(28, 27, 26, 0.9)',
        darkWeatherBgc: '000000',
        dayWeatherFont: 'ffffff',
      },
      // 与header组件通信
      logoText: '小猫咪最可爱啦~',
      showSearch: true,
      navLi: [
        { name: '首页', path: '/home' },
        { name: '分类', path: '/category' },
        { name: '归档', path: '/file' },
        { name: '留言', path: '/message' },
        { name: '友站', path: '/friend' },
        { name: '关于', path: '/brief' },
      ],
      theme: {
        show: true,
      },
      tools: {
        show: true,
        tools: [
          { id: 0, link: 'http://localhost:8080', name: '去后台' },
          { id: 1, link: 'https://gitee.com/jade370/blogs', name: '下载源码' },
          {
            id: 2,
            link: 'https://www.yuque.com/ting-yun/gwxhkg',
            name: '项目文档',
          },
          { id: 3, link: 'https://cloud.tencent.com', name: '腾讯云' },
          { id: 4, link: 'https://www.zhihu.com', name: '知乎' },
          {
            id: 5,
            link: 'https://developer.mozilla.org/zh-CN/docs/Web/API/HTML_DOM_API',
            name: 'MDN',
          },
          { id: 6, link: 'https://v2.cn.vuejs.org/v2/guide/', name: 'VUE' },
          {
            id: 7,
            link: 'https://element.eleme.cn/#/zh-CN',
            name: 'elementUI',
          },
          { id: 8, link: 'https://www.iconfont.cn/', name: '图标库' },
        ],
      },
      user: {
        show: true,
        describe: [
          { id: 'nickname', name: '尚未登录哟~' },
          { id: 'signIn', name: '注册' },
          { id: 'login', name: '登录' },
          { id: 'modify', name: '修改资料' },
          { id: 'signOut', name: '退出' },
        ],
        img: 'default/tx-admin.gif',
      },
      // 用户登陆注册配置
      // 登陆注册对话框显示与否
      centerDialogVisible: false,
      // 修改用户信息对话框显示与否
      updateDialogVisible: false,
      // 登陆注册表单
      loginForm: {
        username: '',
        password: '',
        email: '',
      },
      // 修改用户信息表单
      updateForm: {
        avatar: '',
        username: '',
        password: '',
        email: '',
        nickname: '',
      },
      // 是注册还是登录
      isSignIn: false,
      imageUrl: true,
    }
  },
  created() {
    // 监听滚动事件
    window.addEventListener('scroll', this.handleScroll, true)
    // 获取文章列表
    this.getLoginUser()
  },
  destroyed() {
    //离开这个界面后，清除监听事件
    window.removeEventListener('scroll', this.handleScroll)
  },
  methods: {
    //滚动事件
    handleScroll() {
      //判断滚动条是否位于顶部, 是返回true, 否返回false
      if (document.documentElement.scrollTop > 200) {
        this.backTopShow = true
      } else {
        this.backTopShow = false
      }
    },

    // 根据token获取已登录用户的信息
    getLoginUser() {
      // GET /login/getinfo
      this.$http.get('/login/getinfo').then((res) => {
        // console.log('loginInfo', res)
        const { code, msg, result } = res
        // token合法: 用户已登录
        if (code == 0) {
          this.user.describe = [
            { id: 'nickname', name: '尚未登录哟~' },
            { id: 'modify', name: '修改资料' },
            { id: 'signOut', name: '退出' },
          ]
          // this.user.img = 'yl.jpg'
          this.user.img = result.avatar
          this.user.describe[0].name = result.nickname

          this.updateForm.username = result.username
          this.updateForm.nickname = result.nickname
          this.updateForm.email = result.email
          this.updateForm.password = result.password
          this.updateForm.avatar = result.avatar
          this.imageUrl =
            result.avatar.indexOf('/download/avatar') == -1
              ? 'default/tx-user.svg'
              : result.avatar
          return
        }
        // token 不合法 (如 : 过期, 伪造)
        else if (code == 401) {
          localStorage.removeItem('token')
          this.user.img = 'tx.gif'
        }
        // 其它: 如 未登录
        else {
          this.user.img = 'tx.gif'
          this.user.describe[0].name = '尚未登陆哟~'
        }
        this.user.describe = [
          { id: 'signIn', name: '注册' },
          { id: 'login', name: '登录' },
        ]
      })
    },

    //返回顶部
    backTop() {
      document.documentElement.scrollIntoView({
        block: 'start',
        behavior: 'smooth', // 平滑滚动
      })
    },

    // 改变主题色
    handleChangeTheme(isDark) {
      localStorage.setItem('isDark', isDark)
      this.isDark = isDark
    },

    // 主导航搜索按钮点击事件
    handleSearchClick() {
      this.$message({
        showClose: true,
        message: '您点击了主导航的搜索按钮',
      })
    },

    // 主导航头像下拉列表对应按钮的点击事件
    handleUser(i) {
      // console.log(`您点击了用户下拉列表中id为${i}按钮`)
      // 登录
      if (i == 'login') {
        this.isSignIn = false
        this.centerDialogVisible = true
      }
      // 注册
      else if (i == 'signIn') {
        this.isSignIn = true
        this.centerDialogVisible = true
      }
      // 修改用户信息
      else if (i == 'modify') {
        this.updateDialogVisible = true
        this.$message({
          showClose: true,
          message: '修改资料',
        })
      }
      // 退出
      else if (i == 'signOut') {
        localStorage.removeItem('token')
        this.getLoginUser()
        this.$message({
          showClose: true,
          message: '已登出',
        })
      }
    },

    // 提交登录注册表单
    login() {
      // 登录
      if (!this.isSignIn) {
        // this.$refs['form'].validate((valid) => {
        //   if (valid) {
        this.$http.post(`/login`, this.loginForm).then((res) => {
          if (res.token) {
            localStorage.setItem('token', res.token)
            this.getLoginUser()
            this.$message({
              type: 'success',
              message: '登录成功!',
              showClose: true,
              duration: 1500,
            })
            this.loginForm.username = ''
            this.loginForm.password = ''
            this.loginForm.email = ''
          } else {
            this.$message({
              type: 'error',
              message: '账号或者密码不正确,请重新输入!',
              showClose: true,
              duration: 1500,
            })
          }
          //     })
          // } else {
          //   return false
          // }
        })
      }
      // 注册
      else {
        // this.$refs['form'].validate((valid) => {
        //   if (valid) {
        this.$http.post(`/users`, this.loginForm).then((res) => {
          const { code, msg, result } = res
          if (code == 0) {
            this.$message({
              type: 'success',
              message: '注册成功, 可以登录啦!',
              showClose: true,
              duration: 1500,
            })
            this.loginForm.username = ''
            this.loginForm.password = ''
            this.loginForm.email = ''
          } else if (code == 1) {
            this.$message({
              type: 'error',
              message: '注册失败, 请换个用户名试试!',
              showClose: true,
              duration: 1500,
            })
          } else {
            this.$message({
              type: 'error',
              message: '其它失败原因!',
              showClose: true,
              duration: 1500,
            })
          }
        })
      }
      this.centerDialogVisible = false
    },

    // 取消登录注册
    cancelLogin() {
      this.loginForm.username = ''
      this.loginForm.password = ''
      this.loginForm.email = ''
      this.centerDialogVisible = false
      this.$message({
        showClose: true,
        message: '取消登录注册',
      })
    },

    // 修改用户信息
    update() {
      this.$http
        .put(`/users/${this.updateForm.username}`, this.updateForm)
        .then((res) => {
          const { code, msg, result } = res
          if (code == 0) {
            this.getLoginUser()
            this.$message({
              type: 'success',
              message: '修改成功!',
              showClose: true,
              duration: 1500,
            })
          } else {
            this.$message({
              type: 'error',
              message: '修改失败!',
              showClose: true,
              duration: 1500,
            })
          }
        })
      this.updateDialogVisible = false
    },

    // 取消修改用户信息
    cancelUpdate() {
      this.updateDialogVisible = false
      this.$message({
        showClose: true,
        message: '取消修改用户信息',
      })
    },
    // 图片上传处理函数
    handleSuccessUpload(res, file, fileList) {
      this.imageUrl = res.result.path
      this.updateForm.avatar = res.result.path
    },
    // 约束上传图片的数量
    handleImageExeed(files, fileList) {
      if (files.length === 1) {
        this.$message.error('只能上传一张图片')
      }
    },
    // 约束上传图片类型与大小
    beforeImageUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 5
      if (
        [
          'image/jpeg',
          'image/svg',
          'image/gif',
          'image/jpg',
          'image/png',
        ].indexOf(file.type) === -1
      ) {
        this.$message.error(
          '上传头像图片只能是 JPG , PNG , JPEG, svg, gif 格式!'
        )
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 5MB!')
        return false
      }
    },
  },
  watch: {
    isDark() {
      if (this.isDark == true) {
        document
          .querySelector('body')
          .style.setProperty('--background', this.themeColor.darkBg)
        document
          .querySelector('body')
          .style.setProperty('--color', this.themeColor.darkFont)
        document
          .querySelector('body')
          .style.setProperty('--mask', this.themeColor.darkMask)
        document
          .querySelector('body')
          .style.setProperty('--transparentDiv', this.themeColor.darkOpcityDiv)
        document
          .querySelector('body')
          .style.setProperty('--div', this.themeColor.darkDiv)
        document
          .querySelector('body')
          .style.setProperty('--weather-font', this.themeColor.darkWeatherFont)
        document
          .querySelector('body')
          .style.setProperty('--weather-bgc', this.themeColor.darkWeatherBgc)
      } else {
        document
          .querySelector('body')
          .style.setProperty('--background', this.themeColor.dayBg)
        document
          .querySelector('body')
          .style.setProperty('--color', this.themeColor.dayFont)
        document
          .querySelector('body')
          .style.setProperty('--mask', this.themeColor.dayMask)
        document
          .querySelector('body')
          .style.setProperty('--transparentDiv', this.themeColor.dayOpcityDiv)
        document
          .querySelector('body')
          .style.setProperty('--div', this.themeColor.dayDiv)
        document
          .querySelector('body')
          .style.setProperty('--weather-font', this.themeColor.dayWeatherFont)
        document
          .querySelector('body')
          .style.setProperty('--weather-bgc', this.themeColor.dayWeatherBgc)
      }
    },
  },
}
</script>

<style lang="stylus">
@import '~styles/theme.styl';
@import '~styles/mixins.styl';

.index
  /* 自定义css变量 */
  --header-height: 60px
  --footer-height: 136px
  display: flex
  flex-direction: column
  transition: all 1s ease !important;
  // 使用css变量, 在js中修改css变量值实现昼夜切换
  background: var(--background)
  color: var(--color)
  // &.theme-dark
  //   background: $dark-bg
  //   color: $dark-font
  // &.theme-day
  //   background: $day-bg
  //   color: $day-font

  main
    // background-color: #e9eef3
    // color: #333
    // text-align: center
    // height: calc(100vh - var(--header-height))
    min-height: calc(100vh - var(--footer-height))
  .back-top
    top: -200px;
    cursor: pointer;
    position: fixed;
    right: 40px;
    transition: all .5s ease-in-out;
    animation: float 2s linear infinite;
    &.hide
      top: -900px;
  .el-dialog .el-input
    margin-top: 10px;
  .util
    position : fixed;
    bottom: 20px
    right:20px
@keyframes float
  0%
    transform: translateY(0);
  50%
    transform: translateY(-6px);
  100%
    transform: translateY(0);

/* 滚动条的美化 */
::-webkit-scrollbar
  width: 8px
  height: 8px
::-webkit-scrollbar-corner
  background-color: transparent
::-webkit-scrollbar-thumb
  background-color: #ef8fb2
  background-image: -webkit-linear-gradient(
    45deg,
    hsla(0, 0%, 100%, 0.4) 25%,
    transparent 0,
    transparent 50%,
    hsla(0, 0%, 100%, 0.4) 0,
    hsla(0, 0%, 100%, 0.4) 75%,
    transparent 0,
    transparent
  );
  border-radius: 2em
::-webkit-scrollbar-track
  background-color: rgba(73, 177, 245, 0.2)
  border-radius: 2em
</style>
